import axios from 'axios';
import Qs from 'qs';
import config from '@/config';

// 合并公共参数
let mergeCommonParam = function(type, params) {
  let commonParam = {
    token: config.token,
    userName: config.userName,
    storeCode: config.storeCode,
    siteCode: config.siteCode,
  };
  if (type == 'get') {
    commonParam['_'] = Math.random();
  }
  return Object.assign(commonParam, params);
};

// 清除url上带的指定参数
let cleanUrlParam = function(url, keys) {
  let result = url;
  let urlArray = url.split('?');
  if (urlArray[1]) {
    let urlParam = urlArray[1].split('&');
    urlParam = urlParam.filter((item) => {
      let keep = true;
      for (let key of keys) {
        if (item.indexOf(key + '=') == 0) {
          keep = false;
          break;
        }
      }
      return keep;
    });
    result = `${urlArray[0]}?${urlParam.join('&')}`;
  }
  return result;
};

// axios 配置
const service = axios.create({
  baseURL: config.baseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});
// http response 拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (
      res.soaStateBean &&
      res.soaStateBean.isOk != 1 &&
      res.soaStateBean.isOk != 2
    ) {
      return res;
    } else {
      return res;
    }
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误(400),请请稍后重试！';
          break;
        case 401:
          err.message = '未授权，请重新登录(401)';
          break;
        case 403:
          err.message = '拒绝访问(403),请稍后重试！';
          break;
        case 404:
          err.message = '请求出错(404),请稍后重试！';
          break;
        case 408:
          err.message = '请求超时(408),请稍后重试！';
          break;
        case 500:
          err.message = '服务器错误(500),请稍后重试！';
          break;
        case 501:
          err.message = '服务未实现(501),请稍后重试！';
          break;
        case 502:
          err.message = '网络错误(502),请稍后重试！';
          break;
        case 503:
          err.message = '服务不可用(503),请稍后重试！';
          break;
        case 504:
          err.message = '网络超时(504),请稍后重试！';
          break;
        case 505:
          err.message = 'HTTP版本不受支持(505),请稍后重试！';
          break;
        default:
          err.message = `连接出错(${err.response.status}),请稍后重试！`;
      }
    } else {
      err.message = '连接服务器失败!';
    }
  },
);

// 请求函数
const request = function(url, params = {}, method = 'post', mixins = true) {
  if (method === 'get') {
    return get(url, params, false, mixins);
  } else if (method === 'post') {
    return post(url, params, false, mixins);
  }
};

// get方法
const get = function(
  url,
  params = {},
  trim = true,
  mixins = true,
  loading = true,
) {
  return new Promise(async function(resolve, reject) {
    try {
      // 合并公共参数
      if (mixins) {
        url = cleanUrlParam(url, ['terNo', 'userName', 'siteCode', 'appId']);
        params = await mergeCommonParam('get', params);
      }
      if (typeof params !== 'string') {
        params = Qs.stringify(params);
      }
      url += (url.indexOf('?') > -1 ? '&' : '?') + params;
      let ret = null;
      try {
        if (loading) {
        }
        ret = await service.get(url);
      } catch (error) {}
      if (trim) {
        ret.soaStateBean.isOk == 1 || ret.result
          ? resolve(ret.result)
          : reject(ret);
      } else {
        resolve(ret);
      }
    } catch (e) {
      reject('error');
    }
  });
};
// post方法
const post = function(
  url,
  params = {},
  trim = true,
  mixins = true,
  loading = true,
) {
  return new Promise(async function(resolve, reject) {
    try {
      // 合并公共参数
      if (mixins) {
        url = cleanUrlParam(url, ['terNo', 'userName', 'siteCode']);
        params = await mergeCommonParam('post', params);
      }
      if (typeof params !== 'string') {
        // params = Qs.stringify(params)
      }
      if (config.token && config.userName) {
        url = `${url}?token=${config.token}&userName=${config.userName}&userFromType=0`;
      }
      let ret = null;

      try {
        if (loading) {
        }
        ret = await service.post(url, params);
      } catch (error) {}

      if (trim) {
        ret.soaStateBean.isOk == 1 || ret.result
          ? resolve(ret.result)
          : reject(ret);
      } else {
        resolve(ret);
      }
    } catch (e) {
      reject('error');
    }
  });
};

// 不带结果trim和参数合并的请求方法
const httpGet = (url, params = {}, trim = false, mixins = false) =>
  get(url, params, trim, mixins);
const httpPost = (url, params = {}, trim = false, mixins = false) =>
  post(url, params, trim, mixins);

export { axios, request, get, post, httpGet, httpPost };
